package com.mf.controller;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.DiskFileUpload;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.mf.daoImpl.MusicDaoImpl;
import com.mf.daoImpl.PicLikeDaoImpl;
import com.mf.daoImpl.PictureDaoImpl;
import com.mf.entity.Msg;
import com.mf.entity.Music;
import com.mf.entity.Picture;

public class FileController {

	public Msg fileUpload(HttpServletRequest request, HttpServletResponse response) throws IOException {

		
		//System.out.println(request.getAttribute("title"));
		Msg msg=new Msg();
		Picture pictureMassage=new Picture();
		Music musicMassage=new Music();
		String musicRealnameString=null;
		String picRealnameString = null;
		
		
		
		
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();

		// 设置保存上传文件的目录
		String uploadDir = "/home/upload/imgs";
		//System.out.println("uploadDir==>" + uploadDir );
		File fUploadDir = new File(uploadDir);
		//System.out.println("fUploadDir==>" + fUploadDir);

		if (!fUploadDir.exists()) {
			if (!fUploadDir.mkdir()) {
				return Msg.fail().add("wrong", "无法创建存储目录!");
			}
		}

		if (!DiskFileUpload.isMultipartContent(request)) {
			return Msg.fail().add("wrong", "只能处理multipart/form-data类型的数据!");
		}

		DiskFileUpload fu = new DiskFileUpload();
		// 最多上传200M数据
		fu.setSizeMax(1024 * 1024 * 200);
		// 超过1M的字段数据采用临时文件缓存
		fu.setSizeThreshold(1024 * 1024 * 10);
		// 采用默认的临时文件存储位置
		// fu.setRepositoryPath(...);
		// 设置上传的普通字段的名称和文件字段的文件名所采用的字符集编码
		fu.setHeaderEncoding("utf-8");

		// 得到所有表单字段对象的集合
		List fileItems = null;
		try {
			fileItems = fu.parseRequest(request);
		} catch (FileUploadException e) {

			return Msg.fail().add("wrong", "解析数据时出现如下问题：" + e);
		}
	
		// 处理每个表单字段
		Iterator i = fileItems.iterator();
		while (i.hasNext()) {
			FileItem fi = (FileItem) i.next();
			//System.out.println("fi==>" + fi);
			if (fi.isFormField()) {
				String content = fi.getString("utf-8");
				String fieldName = fi.getFieldName();
				msg.add(fieldName, content);
				//System.out.println("content==>" + content);
				//System.out.println("fieldName==>" + fieldName);
				request.setAttribute(fieldName, content);
			} else {
				try {
					String pathSrc = fi.getName();
					//System.out.println("pathSrc==>" + pathSrc);
					/*
					 * 如果用户没有在FORM表单的文件字段中选择任何文件， 那么忽略对该字段项的处理
					 */
					if (pathSrc.trim().equals("")) {
						continue;
					}
					int start = pathSrc.lastIndexOf("");
					//System.out.println("pathSrc==>" + pathSrc);
					//设置文件名
					String uuID=UUID.randomUUID().toString().replace("-", "");
					
					String oldFileName =fi.getName();
					
					String mytype= oldFileName.substring(oldFileName.lastIndexOf(".")+1);
					
					System.out.println(mytype);
					
					String fileName = uuID+fi.getName();
					//判断文件类型是否正确

						if (mytype.equals("jpg")||mytype.equals("bmp")||mytype.equals("png")||mytype.equals("gif")||mytype.equals("jpeg")) {
							picRealnameString=fileName;
						}else {
							musicRealnameString=fileName;
						}
					
					
		
					
					//System.out.println("fileName==>" + fileName);
					File pathDest = new File(uploadDir, fileName);
					//System.out.println("pathDest==>" + pathDest);
					fi.write(pathDest);
					String fieldName = fi.getFieldName();
					//System.out.println("fieldName==>" + fieldName);
					request.setAttribute(fieldName, fileName);
				} catch (Exception e) {
					out.println("存储文件时出现如下问题：");
					e.printStackTrace(out);
					System.err.println(e);
					return Msg.fail().add("wrong", "存储文件时出现如下问题：" + e);
				} finally // 总是立即删除保存表单字段内容的临时文件
				{
					fi.delete();
				}
			}
		}

		/*
		 * 将上传的文件名组合成"file1,file2"这种形式显示出来，如果没有上传
		 * 任何文件，则显示为"无"，如果只上传了第二个文件，显示为"file2"。
		 */
		
		StringBuffer filelist = new StringBuffer();
		String image = (String) request.getAttribute("image");
		makeUpList(filelist, image);
		String music = (String) request.getAttribute("music");
		makeUpList(filelist, music);
		if (filelist.length() == 0) {
			return Msg.fail().add("successfileulpoad", 0);
		}
		/*开始存入数据库数据*/
		PictureDaoImpl pictureDaoImpl =new PictureDaoImpl();
		MusicDaoImpl musicDaoImpl=new MusicDaoImpl();
		if (msg.getExtend().get("musicname").equals("")||null==msg.getExtend().get("musicname")) {
			System.out.println("音乐未上传");
			if (picRealnameString==null) {
				return Msg.fail();
			}
			pictureMassage.setTitle(msg.getExtend().get("title").toString());
			pictureMassage.setRealname(picRealnameString);
			pictureMassage.setBuilder(msg.getExtend().get("builder").toString());
			pictureMassage.setDetalis(msg.getExtend().get("detalis").toString());
			pictureMassage.setIntro(msg.getExtend().get("intro").toString());
			pictureMassage.setType(msg.getExtend().get("pictype").toString());
			
			pictureDaoImpl.add(pictureMassage);
		}else {
			pictureMassage.setTitle(msg.getExtend().get("title").toString());
			pictureMassage.setRealname(picRealnameString);
			pictureMassage.setBuilder(msg.getExtend().get("builder").toString());
			pictureMassage.setDetalis(msg.getExtend().get("detalis").toString());
			pictureMassage.setIntro(msg.getExtend().get("intro").toString());
			pictureMassage.setType(msg.getExtend().get("pictype").toString());
			pictureMassage.setIsmusicpic(1);
			
			pictureDaoImpl.add(pictureMassage);
			
			musicMassage.setMusicname(msg.getExtend().get("musicname").toString());
			musicMassage.setRealname(musicRealnameString);
			musicMassage.setPictitle(picRealnameString);
			
			musicDaoImpl.add(musicMassage);
		}
		
		/*存入结束*/
		
		return Msg.success().add("successfileulpoad", (filelist.length() == 0 ? "无" : filelist.toString()));
	}
	
	/**
	 * 将一段字符串追加到一个结果字符串中。如果结果字符串的初始内容不为空， 在追加当前这段字符串之前先最加一个逗号（,）。在组合sql语句的查询条件时，
	 * 经常要用到类似的方法，第一条件前没有"and"，而后面的条件前都需要用"and"
	 * 作连词，如果没有选择第一个条件，第二个条件就变成第一个，依此类推。
	 * 
	 * @param result
	 *            要将当前字符串追加进去的结果字符串
	 * @param fragment
	 *            当前要追加的字符串
	 */
	private void makeUpList(StringBuffer result, String fragment) {
		if (fragment != null) {
			if (result.length() != 0) {
				result.append(",");
			}
			result.append(fragment);
		}
	}
}
